<?php

namespace App\Admin\Controllers;

use App\Models\Broadcast;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Str;

class BroadcastsController extends AdminController
{
    protected $title = '广播管理';
    
    protected function grid()
    {
        $grid = new Grid(new Broadcast());

        $grid->column('id', 'ID');
        $grid->column('admin_user_id', '发送者')->display(function () {
        	return $this->adminUser->name;
        });
        $grid->column('message', '消息')->display(function ($value) {
        	return Str::limit($value, 20);
        });
	    $grid->column('expired_at', '到期时间')->display(function () {
	    	return $this->expired_at->toDatetimeString();
	    });
        $grid->column('created_at', '发送时间')->display(function () {
        	return $this->created_at->toDatetimeString();
        });
	
	    $grid->disableRowSelector();
	    $grid->disableExport();
	    $this->gridActions($grid);
        
        return $grid;
    }
	
	protected function gridActions(Grid $grid)
	{
		$grid->actions(function (Grid\Displayers\Actions $actions) {
			$actions->disableView();
			$actions->disableDelete();
		});
	}
    
    protected function detail($id)
    {
        $show = new Show(Broadcast::findOrFail($id));

        $show->field('id', 'ID');
        $show->field('admin_user_id', '发送者');
        $show->field('type', '类型');
        $show->field('message', '消息');
        $show->field('expired_at', '到期时间');
        $show->field('created_at', '发送时间');

        return $show;
    }
    
    protected function form()
    {
        $form = new Form(new Broadcast());

        $form->textarea('message', '消息内容')->rules('required|string');
        $form->datetime('expired_at', '到期时间')->rules('required');
        $form->radio('is_closed', '关闭')->options(config('site.bool'))->default(false);

        $form->saving(function (Form $form) {
        	$form->model()->admin_user_id = Admin::user()->id;
        });
        
        return $form;
    }
}
